<?php
/**
 * 生成一个http请求头header
 * @param mixed $cookie
 * @param mixed $from_ip
 * @return string[]
 */
function make_header($cookie = '', $from_ip = ''): array
{
    $header = array('Content-type: application/x-www-form-urlencoded', 'x-requested-with: XMLHttpRequest', 'Connection: close');
    if ($cookie) {
        $header[] = "Cookie: $cookie";
    }
    if ($from_ip) {
        $header[] = 'CLIENT-IP:' . $from_ip;
        $header[] = 'X-FORWARDED-FOR:' . $from_ip;
    }
    return $header;
}

/**
 * GET网络请求
 * @param $url
 * @param $cookie
 * @param $timeout
 * @param $times
 * @return bool|string
 */
function http_get($url, $cookie = '', $timeout = 30, $times = 3, $from_ip = '')
{
    if (substr($url, 0, 8) == 'https://') {
        return https_send($url, '', $cookie, $timeout, $times, 'GET', $from_ip);
    }
    $header = make_header($cookie, $from_ip);
    $arr = array('http' => array('header' => join("\r\n", $header) . "\r\n", 'method' => 'GET', 'timeout' => $timeout, 'Connection' => "close"));
    $stream = stream_context_create($arr);
    while ($times-- > 0) {
        $s = file_get_contents($url, false, $stream, 0, 4096000);
        if ($s !== FALSE) return $s;
    }
    return FALSE;
}

/*
 * POST网络请求
 * @param $url
 * @param $post
 * @param $cookie
 * @param $timeout
 * @param $times
 * @return bool|mixed|string
 */
function http_post($url, $post = '', $cookie = '', $timeout = 30, $times = 3, $from_ip = '')
{
    $header = make_header($cookie, $from_ip);
    if (strtolower(substr($url, 0, 8)) == 'https://') {
        return https_send($url, $post, $cookie, $timeout, $times, 'post', $from_ip);
    }
    is_array($post) and $post = http_build_query($post);
    is_array($cookie) and $cookie = http_build_query($cookie);
    $stream = stream_context_create(array('http' => array('header' => join("\r\n", $header) . "\r\n", 'method' => 'POST', 'content' => $post, 'timeout' => $timeout)));
    while ($times-- > 0) {
        $s = file_get_contents($url, false, $stream, 0, 4096000);
        if ($s !== FALSE) return $s;
    }
    return FALSE;
}

/**
 * 通用网络请求
 * @param $url
 * @param $post
 * @param $cookie
 * @param $timeout
 * @param $times
 * @param $method
 * @return bool|mixed|string
 */
function https_send($url, $post = '', $cookie = '', $timeout = 30, $times = 1, $method = 'POST', $from_ip = '')
{
    $header = make_header($cookie, $from_ip);
    if (strtolower(substr($url, 0, 7)) == 'http://') {
        if (strtolower($method) == 'post') {
            return http_post($url, $post, $cookie, $timeout, $times, $from_ip);
        } else {
            return http_get($url, $cookie, $timeout, $times, $from_ip);
        }
    }
    is_array($post) and $post = http_build_query($post);
    is_array($cookie) and $cookie = http_build_query($cookie);
    $w = stream_get_wrappers();
    $allow_url_fopen = strtolower(ini_get('allow_url_fopen'));
    $allow_url_fopen = (empty($allow_url_fopen) || $allow_url_fopen == 'off') ? 0 : 1;
    if (extension_loaded('openssl') && in_array('https', $w) && $allow_url_fopen) {
        $stream = stream_context_create(array('http' => array('header' => join("\r\n", $header) . "\r\n", 'method' => $method, 'content' => $post, 'timeout' => $timeout, 'Connection' => "close")));
        $s = file_get_contents($url, false, $stream, 0, 4096000);
        return $s;
    } elseif (!function_exists('curl_init')) {
        return 'server not installed curl.';
    }
    $ch = curl_init();
    $options = array(
        'CURLOPT_URL' => $url,
        'CURLOPT_CUSTOMREQUEST' => 'POST',
        'CURLOPT_RETURNTRANSFER' => true,
        'CURLOPT_HEADER' => 2,
        'CURLOPT_HTTPHEADER' => $header,
        'CURLOPT_USERAGENT' => getServer('HTTP_USER_AGENT'),
        'CURLOPT_SSL_VERIFYPEER' => 0,
        'CURLOPT_SSL_VERIFYHOST' => 2,
        'CURLOPT_TIMEOUT' => $timeout,
    );

    if (strtolower($method) == 'post') {
        $options['CURLOPT_POST'] = 1;
        $options['CURLOPT_POSTFIELDS'] = $post;
    }
    (!ini_get('safe_mode') && !ini_get('open_basedir')) && $options['CURLOPT_FOLLOWLOCATION'] = 1;

    foreach ($options as $option => $value) {
        curl_setopt($ch, constant($option), $value);
    }

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        return 'Errno' . curl_error($ch);
    }
    if (!$data) {
        curl_close($ch);
        return '';
    }
    list($header, $data) = explode("\r\n\r\n", $data);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        $matches = array();
        preg_match('/Location:(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $data = curl_exec($ch);
    }
    curl_close($ch);
    return $data;
}

/**
 * 随机生产一个有效的随机IPv4地址
 */
function make_ipv4()
{
    return rand(1, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);
}

/** 获取远程图片并把它保存到服务器
 * @param string $url 是远程图片的完整URL地址，不能为空。
 * @param string $save_filename 是可选变量: 如果为空，本地文件名将基于时间和日期
 * @return bool
 */
function http_downfile($url, $save_filename = "")
{
    if ($url == "")
        return false;
    if ($save_filename == "") {
        $save_filename = date("dMYHis");
    }
    $data = http_get($url);
    if (!$data) {
        return false;
    }
    $fp2 = @fopen($save_filename, "w+");
    fwrite($fp2, $data);
    fclose($fp2);
    return true;
}